package com.example.campuslink.commen.db.school

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.campuslink.commen.db.InvitationTableConverter
import com.example.campuslink.commen.db.MessageBeanConverter
import com.example.campuslink.commen.db.SearchDataConverter
import com.example.campuslink.commen.db.userNumber.ListMessageTableConverter
import db.ListStringConverter

@Database(entities = [SchoolInfoTable::class], version = 4, exportSchema = true)
@TypeConverters(
    ListStringConverter::class,
    InvitationTableConverter::class,
    SearchDataConverter::class,
    ListMessageTableConverter::class
)
abstract class SchoolInfoData : RoomDatabase() {
    abstract fun schoolInfoDao(): SchoolInfoDao

    val MIGRATION_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE school_info_table ADD COLUMN mainInvitationList TEXT")
            database.execSQL("ALTER TABLE school_info_table ADD COLUMN shoppingInvitationList TEXT")
        }
    }
    val MIGRATION_2_3 = object : Migration(2, 3) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE school_info_table ADD COLUMN searchData TEXT")
        }
    }
    val MIGRATION_3_4 = object : Migration(3, 4) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE school_info_table ADD COLUMN messageList TEXT")
        }
    }

    companion object {
        @Volatile
        private var INSTANCE: SchoolInfoData? = null

        fun getDatabase(context: Context): SchoolInfoData {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    SchoolInfoData::class.java,
                    "school_info_dataBase"
                )
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}